package com.example.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.dto.VisitStats;
import com.example.mapper.VisitStatsMapper;
import com.example.service.VisitStatsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 访问统计服务实现类
 *
 * @auth shanyue
 * @date 2025年08月06日10:55
 */
@Service
@Slf4j
public class VisitStatsServiceImpl extends ServiceImpl<VisitStatsMapper, VisitStats> implements VisitStatsService {

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Resource
    private VisitStatsMapper visitStatsMapper;

    /**
     * 定时认识，每天凌晨1执行，将前一天的访问量数据持久化到数据库
     * 并清理Redis中前一天的访问量技术及UV集合
     */
    @Override
    @Scheduled(cron = "0 0 1 * * ?")
    public void saveDailyVisitDate() {

        log.info("执行访问量持久化任务");

        //计算昨天的日期字符串
        String yesterday = LocalDate.now().minusDays(1).toString();

        //Redis中对对应的访问量和UV集合的key
        String dailyKey = "visit:" + yesterday;
        String uvKey = "uv:" + yesterday;
        String totalKey = "visit:total";

        //从Redis读取昨天的访问量和总访问量
        String dailyCountStr = redisTemplate.opsForValue().get(dailyKey);
        String totalCountStr = redisTemplate.opsForValue().get(totalKey);

        //解析访问量
        long dailyCount = dailyCountStr != null ? Long.parseLong(dailyCountStr) : 0L;
        long totalCount = totalCountStr != null ? Long.parseLong(totalCountStr) : 0L;

        //构建访问量
        VisitStats stats = new VisitStats();
        LocalDateTime now = LocalDateTime.now();
        stats.setVisitData(LocalDate.parse(yesterday));
        stats.setCount(dailyCount);
        stats.setTotal(totalCount);
        stats.setCreateTime(now);
        stats.setUpdateTime(now);

        //插入数据库
        visitStatsMapper.insert(stats);

        // 清除昨日访问计数及UV集合
        redisTemplate.delete(dailyKey);
        redisTemplate.delete(uvKey);

        log.info("持久化访问数据成功: 日期 {}，访问量 {}，总访问量 {}", yesterday, dailyCount, totalCount);
    }

    /**
     * 分页查询访问统计数据
     *
     * @param page 分页参数
     * @return 分页结果
     */
    @Override
    public IPage<VisitStats> getVisitStatsPage(Page<VisitStats> page) {
        return visitStatsMapper.selectPage(page, null);
    }
}
